package net.lummox.model;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

public class DictionaryDao extends CommonDaoImpl<Dictionary> {

	private final String SELECT_QUERY = "select id, word from dictionary where id = :id";
	private final String SELECT_ALL_QUERY = "select id, word from dictionary order by id";
	private final String INSERT_SQL = "{call dictionary_insert(?, ?)}";
	private final String UPDATE_SQL = "{call dictionary_update(?, ?)}";

	public DictionaryDao() {
		super();
		type = Dictionary.class;
	}

	@Override
	protected Dictionary createModelFromResultSet(ResultSet rs) {

		Dictionary dict = null;

		try {
			dict = new Dictionary();

			dict.setId(rs.getInt(1));
			dict.setWord(rs.getString(2));

		} catch (SQLException e) {
			logger.error(e);
		}

		return dict;
	};

	@Override
	public int insert(Dictionary t) {
		try {

			getInsertStatement().setString(1, t.getWord());
			getInsertStatement().registerOutParameter(2, Types.INTEGER);
			getInsertStatement().execute();
			
			return getInsertStatement().getInt(2); 
					
		} catch (SQLException e) {
			logger.error(e);
			return -1;
		}
	}

	@Override
	public boolean update(Dictionary t) {
		try {
			getUpdateStatement().setInt(1, t.getId());
			getUpdateStatement().setString(2, t.getWord());

			getUpdateStatement().executeUpdate();
			return true;
		} catch (SQLException e) {
			logger.error(e);
			return false;
		}
	}

	@Override
	public Dictionary getById(int id) {

		Dictionary dict = null;

		try {
			ResultSet rs = getSelectStatement(id).executeQuery();

			if (rs != null) {
				if (rs.next()) {
					dict = createModelFromResultSet(rs);
				}
			}

		} catch (SQLException e) {
			logger.error(e);
		}

		return dict;

	}

	@Override
	public List<Dictionary> getAll() {

		List<Dictionary> list = null;
		Dictionary dict;

		try {
			ResultSet rs = getSelectAllStatement().executeQuery();
			if (null != rs) {
				
				if (rs.next()) {
					list = new ArrayList<Dictionary>();
				}
				
				do {
					dict = createModelFromResultSet(rs);
					if (null != dict) {
						list.add(dict);
					}
				} while ((rs.next()));
			}

		} catch (SQLException e) {
			logger.error(e);
		}

		return list;
	}

	@Override
	protected String getSelectAllSql() {
		return SELECT_ALL_QUERY;
	}

	@Override
	protected String getSelectSql() {
		return SELECT_QUERY;
	}

	@Override
	protected String getInsertSql() {
		return INSERT_SQL;
	}

	@Override
	protected String getUpdateSql() {
		return UPDATE_SQL;
	}

	private Logger logger = Logger.getLogger(Dictionary.class);
	
}
